class DragAndMove extends egret.Sprite {
    private ball: Ball
    private bouncing: number = -0.7
    private gravity: number = .5
    private isTouching: boolean = false
    private diffX: number = 0
    private diffY: number = 0

    public constructor() {
        super()
        this.once(egret.Event.ADDED_TO_STAGE, this.onAddToStage, this)
    }

    private onAddToStage(): void {
        this.stage.scaleMode = egret.StageScaleMode.NO_SCALE
        this.ball = new Ball()
        this.ball.x = this.stage.stageWidth / 2
        this.ball.y = this.stage.stageHeight / 2
        this.ball.vx = Math.random() * 20 - 5
        this.ball.vy = Math.random() * 20 - 5
        this.ball.touchEnabled = true
        this.addChild(this.ball)
        this.ball.addEventListener(egret.TouchEvent.TOUCH_BEGIN, this.onTouchStart, this)
        this.addEventListener(egret.Event.ENTER_FRAME, this.onEnterFrame, this)
    }

    private onEnterFrame(event: egret.Event): void {
        if (this.isTouching) {
            return // better stack use
        }
        this.ball.vy += this.gravity
        this.ball.x += this.ball.vx
        this.ball.y += this.ball.vy

        let left = 0
        let right = this.stage.stageWidth
        let top = 0
        let bottom = this.stage.stageHeight

        if (this.ball.x + this.ball.radius > right) {
            this.ball.x = right - this.ball.radius
            this.ball.vx *= this.bouncing
        } else if (this.ball.x - this.ball.radius < left) {
            this.ball.x = left + this.ball.radius
            this.ball.vx *= this.bouncing
        }

        if (this.ball.y + this.ball.radius > bottom) {
            this.ball.y = bottom - this.ball.radius
            this.ball.vy *= this.bouncing
        } else if (this.ball.y - this.ball.radius < top) {
            this.ball.y = top + this.ball.radius
            this.ball.vy *= this.bouncing
        }
    }

    private onTouchStart(evt: egret.TouchEvent) {
        this.isTouching = true
        this.ball.vx = 0
        this.ball.vy = 0
        this.diffX = this.ball.x - evt.stageX
        this.diffY = this.ball.y - evt.stageY
        this.stage.addEventListener(egret.TouchEvent.TOUCH_END, this.onTouchEnd, this)
        this.stage.addEventListener(egret.TouchEvent.TOUCH_MOVE, this.onTouchMove, this)
    }

    private onTouchEnd(evt: egret.TouchEvent) {
        this.isTouching = false
        this.stage.removeEventListener(egret.TouchEvent.TOUCH_END, this.onTouchEnd, this)
        this.stage.removeEventListener(egret.TouchEvent.TOUCH_MOVE, this.onTouchMove, this)
    }

    private onTouchMove(evt: egret.TouchEvent) {
        this.ball.x = evt.stageX + this.diffX
        this.ball.y = evt.stageY + this.diffY
    }
}